// eslint-disable-next-line
// eslint-disable-next-line
import {treeBuild} from "@/utils/index";
import {BasicLayout, BlankLayout, PageView, RouteView,} from "@/layouts";
import {constantRouterMap} from '@/config/router.config'
import {setting} from "@/core/icons";

// 前端路由表
const constantRouterComponents = {
    // 基础页面 layout 必须引入
    BasicLayout: BasicLayout,
    BlankLayout: BlankLayout,
    RouteView: RouteView,
    PageView: PageView,
    "403": () => import(/* webpackChunkName: "error" */ "@/views/exception/403"),
    "404": () => import(/* webpackChunkName: "error" */ "@/views/exception/404"),
    "500": () => import(/* webpackChunkName: "error" */ "@/views/exception/500"),


    BlankLayoutHeader: () => import('@/layouts/BlankLayoutHeader'),
    // 你需要动态引入的页面组件
    /*
     *系统设置
     * */
    //数据字典
    datadictionary: () => import("@/views/admin/system/datadictionary"),
    //组织架构
    structure: () => import("@/views/admin/system/structure"),
    //人员管理
    personnelinfo: () => import("@/views/admin/system/personnelinfo"),
    //模块管理
    modulement: () => import("@/views/admin/system/modulement"),
    //角色管理
    rolement: () => import("@/views/admin/system/rolement"),
    //菜单管理
    menument: () => import("@/views/admin/system/menument"),
    //访问日志
    sysAccessLog: () => import("@/views/admin/system/sysAccessLog"),
    // 短信日志
    sysAccesysSmsLogssLog: () => import("@/views/admin/system/sysSmsLog"),
    //邮件日志
    sysEmailLog: () => import("@/views/admin/system/sysEmailLog"),
    //系统配置
    sysconfig: () => import("@/views/admin/system/sysConfig")
};

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
    path: "*",
    redirect: "/404",
    // component: () => import(/* webpackChunkName: "error" */ "@/views/exception/404"),
    hidden: true
};

// 根级菜单
const rootRouter = {
    path: '/',
    name: '管理系统',
    redirect: '/user_info',
    component: 'BlankLayout',
    meta: {
        title: '管理系统'
    },
    children: []
};

/**
 * 动态生成菜单
 * @param token
 * @param data  菜单
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = res => {
    return new Promise((resolve, reject) => {
        let tree = treeBuild(res);
        const menuNav = [];
        const childrenNav = tree;
        //      后端数据, 根级树数组,  根级 PID
        // listToTree(result, childrenNav, 0);
        rootRouter.children = childrenNav;
        menuNav.push(rootRouter);
        const routers = generator(menuNav);
        routers.push(notFoundRouter);
        let router = routers.concat(constantRouterMap)
        resolve(router);
    });
};

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
    return routerMap.map((item, index) => {
        if (item.type != 2) {
            const currentRouter = {
                // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
                path: item.webUrl || item.path,
                // 路由名称，建议唯一
                name: item.name || "",
                // 该路由对应页面的 组件 :方案1
                // component: constantRouterComponents[item.component],
                // 该路由对应页面的 组件 :方案2 (动态加载)
                component:
                    constantRouterComponents[item.component] ||
                    (() => import(`@/views/${item.component}`)),

                // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
                meta: {
                    title: item.name,
                    icon: item.logoUrl || undefined,
                    icons: item.logoCheckUrl || undefined,
                    hiddenHeaderContent: item.hiddenHeaderContent || undefined,
                    target: item.target || undefined,
                    permission: item.authority || []
                }
            };
            if (item.webUrl === '/admin/system') {
                currentRouter.meta.icon = setting
            }
            if (item.childList && item.childList.length > 0) {
                currentRouter.children = item.childList;
            } else {
                currentRouter.children = item.children;
            }
            // 是否设置了隐藏菜单
            if (item.status === 1) {
                currentRouter.hidden = true;
            }

            // 是否设置了隐藏子菜单
            if (item.hideChildrenInMenu === 1) {
                currentRouter.hideChildrenInMenu = true;
            }
            // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
            // if (!currentRouter.path.startsWith("http")) {
            //   currentRouter.path = currentRouter.path.replace("//", "/");
            // }
            // 重定向
            if (item.redirect) {
                currentRouter.redirect = item.redirect;
            }
            item.redirect && (currentRouter.redirect = item.redirect);
            // 是否有子菜单，并递归处理
            if (item.children) {
                // Recursion
                currentRouter.children = generator(item.children, currentRouter);
            }

            return currentRouter;
        }
    });
};

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId) {
            const child = {
                ...item,
                key: item.key || item.name,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            tree.push(child);
        }
    });
};
